package com.xifly.controller;

import com.xifly.bean.UserInfo;
import com.xifly.jwt.Audience;
import com.xifly.repository.UserInfoRepository;
import com.xifly.utils.ResultMsg;
import com.xifly.utils.ResultStatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private Audience audience;

    @RequestMapping("getuser")
    public Object getUser(int id){
        UserInfo userInfo = userInfoRepository.findUserInfoById(id);
        ResultMsg resultMsg = new ResultMsg(ResultStatusCode.OK.getErrorcode(),ResultStatusCode.OK.getErrormsg(),userInfo);
        return resultMsg;
    }

    @RequestMapping("getusers")
    public Object getUsers(String role){
        List<UserInfo> userInfos = userInfoRepository.findUserInfoByRole(role);
        ResultMsg resultMsg = new ResultMsg(ResultStatusCode.OK.getErrorcode(),ResultStatusCode.OK.getErrormsg(),userInfos);
        return resultMsg;
    }

    @Modifying
    @RequestMapping("adduser")
    public Object addUser(@RequestBody UserInfo userInfo){
        UserInfo user = userInfoRepository.save(userInfo);
        ResultMsg resultMsg = new ResultMsg(ResultStatusCode.OK.getErrorcode(),ResultStatusCode.OK.getErrormsg(),user);
        return resultMsg;
    }

    @Modifying
    @RequestMapping("updateuser")
    public Object updateUser(@RequestBody UserInfo userInfo){
        UserInfo user = userInfoRepository.findUserInfoById(userInfo.getId());
        if (user != null){
            user.setName(userInfo.getName());
            userInfoRepository.save(user);
        }
        ResultMsg resultMsg = new ResultMsg(ResultStatusCode.OK.getErrorcode(),ResultStatusCode.OK.getErrormsg(),user);
        return resultMsg;
    }

    @Modifying
    @RequestMapping("deleteuser")
    public Object deleteUser(int id){
        userInfoRepository.delete(id);
        ResultMsg resultMsg = new ResultMsg(ResultStatusCode.OK.getErrorcode(),ResultStatusCode.OK.getErrormsg(),null);
        return resultMsg;
    }

    @RequestMapping("getaudience")
    public Object getAudience(){
        ResultMsg resultMsg = new ResultMsg(ResultStatusCode.OK.getErrorcode(),ResultStatusCode.OK.getErrormsg(),audience);
        return resultMsg;
    }
}
